Image Resolutions for a CSS "background-image"
To enable browsers to automatically select the most suitable CSS background-image
depending on resolution, you can use the CSS image-set()
function. This function allows you to offer multiple image choices, and define their corresponding resolutions using the CSS <resolution>
data type:
background-image: image-set(
url("image.jpg") 1x,
url("image-2x.jpg") 2x
);
With this, the image-set()
function allows the browser to select the most appropriate image (from the provided set of images) based on the user's device pixel ratio (DPR). If the user's DPR matches one of the specified values, that image is used. Otherwise, the browser chooses the closest match.
If you wish to support browsers that do not support image-set()
, you may have to add vendor prefixes and/or include a fallback before the "image-set()
" declaration.
For example, you can add a fallback before the "image-set()
" declaration in the following way:
.foo {
background-image: url("image.jpg"); /* fallback for browsers
that do not support image-set() */
background-image: image-set(url("image.jpg") 1x, url("image-2x.jpg") 2x);
}
This ensures that browsers that do not support image-set()
will still display the background image as expected.